<template>
  <!-- 登录组件 -->

  <!-- 饿了么表单 -->
  <el-form ref="form" :model="form" class="form" :rules="rules">
    <!-- 手机号 -->
    <el-form-item class="form-item" prop="username">
      <el-input placeholder="用户名/手机" v-model="form.username" @focus="clearRules('username')"></el-input>
    </el-form-item>
    <!-- 密码 -->
    <el-form-item class="form-item" prop="password">
      <el-input
        type="password"
        placeholder="密码"
        v-model="form.password"
        @focus="clearRules('password')"
      ></el-input>
    </el-form-item>

    <!-- 忘记密码 -->
    <p class="form-text">
      <nuxt-link to="#">忘记密码</nuxt-link>
    </p>
    <!-- 登录按钮 -->
    <el-button type="primary" class="submit" @click="handleLoginSubmit">登录</el-button>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      //表单对象数据
      form: {
        username: "",
        password: ""
      },
      //校验规则
      rules: {
        username: [
          {
            //required:所需    message：错误提示信息    trigger：触发条件
            required: true,
            message: "请输入用户名或手机号码",
            trigger: "blur"
          },
          //最小6位，最大11位，失去焦点触发
          { min: 6, max: 11, message: "长度在 6 到 11 个字符", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  //方法
  methods: {
    //1.聚焦,清除检验出错提醒信息
    clearRules(index) {
      this.$refs.form.clearValidate(index);
    },

    //2.提交按钮事件
    handleLoginSubmit() {
      console.log(this.form);

      //提交之前，form表单全部验证一次
      this.$refs.form.validate(valid => {
        //res为true，则验证成功
        if (valid) {
          //调用vuex封装的登录请求
          this.$store.dispatch("user/login", this.form).then(res => {
            console.log(res.data);
            //登录成功，发起文字弹框
            this.$message.success("登录成功");
            this.$store.state.user.userInfo.order = "order";
            //判断当前路径是不是机票订单页，是的话不进行跳转
            if (this.$route.path != "/air/order") {
              //跳转到首页
              this.$router.push("/");
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
//elm表单
.form {
  padding: 25px;
  //表单项
  .form-item {
    margin-bottom: 20px;
  }
  //忘记密码
  .form-text {
    font-size: 12px;
    color: #409eff;
    text-align: right;
    line-height: 1;
  }
  //提交按钮
  .submit {
    width: 100%;
    margin-top: 10px;
  }
}
</style>